/**
 * rectwidget
 * 系统内建核心组件. 为系统提供区域的Widget (className: DSV_RegionWidget)
 */

var FG;
if (!FG)
    FG = {};

FG.RECTWIDGET_TEMPLATE = _.template(
    '<div class="toolwidget">' +
        //'<div class="name" >点</div>' +
        //'<div class="lonlat">123.45123°E 40.00234°N</div>' +
        '<input class="name_edit" type="text" />' +
        '<input class="lonlat_edit" type="text" readonly/>' +
        '<div class="sample_label inactive">样品</div>' +
        '<div class="button delete_this layer"><i class="fa fa-times-circle"></i></div>' +
        '<div class="button camera layer" title="快照"><i class="fa fa-camera"></i></div>' +
        '<div class="button_row">' +
            '<div class="button buy inactive" title="购买"><i class="fa fa-shopping-cart "></i></div>' +
            '<div class="button ds" title="物理量列表"><i class="fa fa-list-alt"></i></div>' +
            '<div class="button download" title="下载"><i class="fa fa-download"></i></div>' +
            '<div class="button edit" title="编辑描述信息"><i class="fa fa-edit"></i></div>' +
                //'<div class="button min"><i class="icon "></i></div>' +
            '<div class="button snapshots" title="查看快照列表和删除"><i class="fa fa-caret-square-o-right"></i>/<i class="fa fa-trash"></i></div>' +
            '<div class="photo_port"></div>' +
        '</div>' +
        //'<div class="button snapshots"><i class="icon-expand "></i></div>' +
        '<div class="ds_box toolbox">' +
            '<select class="dataset" title="数据集"></select>' +
            '<ul class="subset">' +
            '</ul>' +
        '</div>' +
        '<div class="buy_box toolbox"></div>' +
        '<div class="edit_box toolbox"></div>' +
        '<div class="download_box toolbox"></div>' +
        '<div class="snapshot_box toolbox"></div>' +
        '<div class="coorder_box">' +
            //'<div class="fg_label vertical_text coord_label level_coord_label">高度层</div>' +
            '<div class="coord_box level_coord_box"></div>' +
            //'<div class="fg_label coord_label version_coord_label">版本</div>' +
            '<div class="coord_box version_coord_box"></div>' +
            //'<div class="fg_label coord_label time_coord_label">时间</div>' +
            '<div class="coord_box time_coord_box"></div>' +
        '</div>' +
        '<div class="colorbar_box">' +
            '<div class="button colorbar_fix" title="固定数据范围"><i class="fa fa-anchor"></i></div>' +
            '<div class="button colorbar_fit" title="适应数据范围"><i class="fa fa-arrows-v"></i></div>' +
            '<div class="colorbar_svg"></div>' +
            '<div class="colorbar_units"></div>' +
        '</div>' +
        '<div class="alpha_box" title="调整透明度 (按住Ctrl键点击可切换至完全透明)">' +
            '<div class="button alpha_button alpha_toggle1">透明度</div>' +
            '<div class="button alpha_button alpha_toggle2">透明度</div>' +
            '<div class="button alpha_button alpha_toggle3">透明度</div>' +
        '</div>' +
        //'<div class="snapshot_box toolbox"></div>' +
    '</div>' //+
);

FG.RectWidget = FG.FeatureDSVWidgetBase.extend({
    statics: {
        className: 'DSV_RegionWidget'
    },
    
    options: {
        minWidth: 20,
        maxWidth: 300,
        // maxHeight: null,
        autoPan: false,
        closeButton: false,
        offset: [3, 2],
        //autoPanPadding: [45, 10],
        autoPanPaddingTopLeft: [300, 10],
        autoPanPaddingBottomRight: [10, 10],
        keepInView: true,
        zoomAnimation: true,
        className: '',
        widgetClassName: 'rectwidget',
        widgetTemplate: FG.RECTWIDGET_TEMPLATE,
        widgetPrefix: 'leaflet-rectwidget',
        widgetType: 'rect'
    },
    
    
    _updatePosition: function () {
        if (!this._map) {
            return;
        }

        var ne = this._source ? this._source.getBounds().getNorthEast() : this._latlng;
        //var pos = this._map.latLngToLayerPoint(this._latlng),
        var pos = this._map.latLngToLayerPoint(ne),
            animated = this._animated,
            offset = L.point(this.options.offset);

        if (animated) {
            L.DomUtil.setPosition(this._container, pos);
        }

        //this._containerBottom = -offset.y - (animated ? 0 : pos.y);
        //this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
        this._containerTop = -offset.y - (animated ? 0 : pos.y);
        this._containerLeft = offset.x + (animated ? 0 : pos.x);
        this._containerBottom = this._containerTop - this._container.offsetHeight;

        //var mapSize = this._map.getSize();
        //var maxLeft = mapSize.x - this._containerWidth;
        //this._containerLeft = this._containerLeft > maxLeft ? maxLeft : this._containerLeft;

        // bottom position the popup in case the height of the popup changes (images loading etc)
        this._container.style.top = this._containerTop + 'px';
        //this._container.style.bottom = this._containerBottom + 'px';
        this._container.style.left = this._containerLeft + 'px';
    },

    _zoomAnimation: function (opt) {
        var ne = this._source ? this._source.getBounds().getNorthEast() : this._latlng;
        var pos = this._map._latLngToNewLayerPoint(ne, opt.zoom, opt.center);
        L.DomUtil.setPosition(this._container, pos);
    },

    _updateLayout: function () {
        var container = this._contentNode,
            style = container.style;

        style.width = '';
        style.whiteSpace = 'nowrap';

        var width = container.offsetWidth;
        width = Math.min(width, this.options.maxWidth);
        width = Math.max(width, this.options.minWidth);

        style.width = (width + 1) + 'px';
        style.whiteSpace = '';

        style.height = '';

        var height = container.offsetHeight,
            maxHeight = this.options.maxHeight,
            scrolledClass = 'leaflet-popup-scrolled';

        if (maxHeight && height > maxHeight) {
            style.height = maxHeight + 'px';
            L.DomUtil.addClass(container, scrolledClass);
        } else {
            L.DomUtil.removeClass(container, scrolledClass);
        }

        this._containerWidth = this._container.offsetWidth;
    },

    renderModel: function(model) {
        var this_ = this;
        this._renderModelBasic(model);
        this._renderTools();
        this.$figure = this._source.$image;
        this.$name_edit.val(model.get('name'));
        var info  = model.get('info');
        if (!!info && _.has(info, 'lat1') && _.has(info, 'lon1')
                   && _.has(info, 'lat2') &&_.has(info, 'lon2')) {
            var llstr = info.lat1.toFixed(5) + '~' + info.lat2.toFixed(5) + '°N '+
                        info.lon1.toFixed(5) + '~' + info.lon2.toFixed(5) + '°E' ;
            this.$lonlat_edit.val(llstr);
        } else if (model.has('geometry_uri')) {
            this.$lonlat_edit.val(model.get('geometry_uri'));
        }

        this.coorderView = new FG.CoorderView({
            el: this.$content.find('.coorder_box')
        });

        this.cmap = FG.getColormap(FG.getDefaultCmap());
        this.$colorbar = this.$content.find('.colorbar_box .colorbar_svg');
        var myScale = d3.scale.linear()
                        .range(this.cmap.get('colors'))
                        .domain(DX.linspace(0, 12, this.cmap.get('color_number')));
        this.$colorbarUnits = this.$content.find('.colorbar_box .colorbar_units');
        this.colorbar = Colorbar()
            .thickness(10).barlength(109)
            .margin({top:5, bottom:25, left:0, right:35})
            .origin([0,0])
            //.scale(myScale)
            .orient("vertical");

        this.colorbarObject = d3.select(this.$colorbar[0]);
                                //.call(this.colorbar);

        var alphaToggles = {
            alpha1: this.$content.find('.alpha_box .alpha_button.alpha_toggle1'),
            alpha2: this.$content.find('.alpha_box .alpha_button.alpha_toggle2'),
            alpha3: this.$content.find('.alpha_box .alpha_button.alpha_toggle3')
        };
        var alphaActions = {
            alpha1: function() { this_._source.setImageOpacity(1.0)},
            alpha2: function() { this_._source.setImageOpacity(0.6)},
            alpha3: function() { this_._source.setImageOpacity(0.0)}
        };

        this.alphaToggler = new DX.Toggler(alphaToggles, {"default": 'alpha2', actions: alphaActions});
        this.$content.find('.alpha_box .alpha_button')
            .unbind('click').
            click(function() {
                var lastAlpha = this_.alphaToggler.value();
                if (ctrlPressed) {
                    if (lastAlpha === 'alpha3') {
                        this_.alphaToggler.toggle();
                    } else {
                        this_.alphaToggler.toggle('alpha3');
                    }
                } else {
                    if (lastAlpha === 'alpha1') {
                        this_.alphaToggler.toggle('alpha2');
                    } else if (lastAlpha === 'alpha2') {
                        this_.alphaToggler.toggle('alpha1');
                    } else {
                        this_.alphaToggler.toggle('alpha2');
                    }
                }
            });

        var vrangeToggles = {
            fix: this.$content.find('.colorbar_box .colorbar_fix'),
            fit: this.$content.find('.colorbar_box .colorbar_fit')
        };
        this.vrangeToggler = new DX.Toggler(vrangeToggles, {"default": "fix"});
        _.each(vrangeToggles, function(button, name) {
            button.unbind('click').click(function() {
                this_.vrangeToggler.toggle(name);
                this_.switchViewport({type: "refresh"})
            })
        });

        this._renderDSV();

        this.setContent(this.$content[0]);
        this._switchDefaultViewport();
        return this;
    },
    
    _renderDSV: function() {
        var this_ = this,
            model = this.model,
            content = this.$content;
    
        _.each([
            'dataset', 'subset'
        ], function (elem) {
            this_['$' + elem] = content.find('.ds_box').find('.' + elem);
        });
        this.svView = new FG.SVView({
            target: this.$subset,
            subsetLiTemp: _.template(
                '<li class="subset_tab subset_<%= name %>">' +
                '<a class="head"><%= zhName %></a>' +
                '<div class="body nano">' +
                '<ul class="var_list nano-content"></ul>' +
                '</div>' +
                '</li>'
            ),
            varLiTemp: _.template('<li class="var var_<%= name %>"><%= zhName %></li>')
        });
        
        this.$dataset.empty();
        if (_.has(model, 'dsvList') && !_.isEmpty(model.dsvList)) {
            _.each(model.dsvList, function (ds) {
                var data = {dstype: "normal"};
                _.extend(data, ds);
                var $dsItem = $(FG.WIDGET_DATASET_TEMPLATE(data));
                this_.$dataset.append($dsItem);
            });
        }
        
        var app = DX.get('app', null);
        // if (!!app) {
        //     if (app.hasModule('nwp_port')) {
        //         var data = {dstype: 'tool', name: 'nwp_port', desc: '新增中尺度数值模拟项目', zh_name: '新建中尺度模拟'}
        //         var $dsItem = $(FG.WIDGET_DATASET_TEMPLATE(data));
        //         this_.$dataset.append($dsItem);
        //     }
        // }
        //关联事件等逻辑
    
        // 数据集选择
        this.$dataset.unbind('change').change(function (e) {
            DX.warn('Changed!: ' + this_.$dataset.val());
            var dsName = this_.$dataset.val();
            var dsType = this_.$dataset.find('option:selected').attr('type');
            if (!_.isNull(dsName)) {
                if (dsType === 'normal') {
                    this_.switchDataset(dsName);
                } else if (dsType === 'tool') {
                    var tool;
                    if (!!app) {
                        tool = app.getModule(dsName);
                    } else {
                        tool = DX.get(dsName, null);
                    }
                    if (!!tool) {
                        tool.act({
                            pitem: this_.model,
                            feature: this_._source,
                            widget: this_
                        });
                    }
                }
            }
        });
        
        this.$dataset.trigger('change');
    
        // this.once('open', function () {
        //     this_.svView.onResize();
        // });
    
        return this;
    },
    
    // 切换工具框

    plotFigure: function(variable, parameters, target, callback) {
        var dataBundle = variable.getDataBundle();
        var coordsUri = variable.coorder.getReplacedUris().join('/');
        var fullUri = [variable.uri, coordsUri].join('/');
        this._source.plotData(dataBundle, {callback: callback, uri: fullUri, widget: this, vrange: this.vrangeToggler.value()});
    },


    setColorbar: function(opts) {
        opts = _.extend({
            cmap: FG.getDefaultCmap(),
            vmin: 0,
            vmax: 1,
            units: ''
        }, opts);

        this.cmap = FG.getColormap(opts.cmap);
        var scale = d3.scale.linear()
                      .range(this.cmap.get('colors'))
                      .domain(DX.linspace(opts.vmin, opts.vmax, this.cmap.get('color_number')));
        this.colorbar.scale(scale);
        this.colorbarObject.call(this.colorbar);
        this.$colorbarUnits.html(opts.units);
    }
});

//
// FG.getRectWidget = function(opts, widgetOpts, source) {
//     this.widgetOpts = _.extend({}, widgetOpts);
//     //var widgetContent = FG.RECTWIDGET_TEMPLATE(this.content.model.attributes);
//     var widget = new FG.RectWidget(this.widgetOpts, source);
//     //widget.setContent(widgetContent);
//     return widget;
// };


